import React, { useReducer, useEffect, useState } from 'react';
import { Toast } from 'antd-mobile';
import TitleBack from '../../components/TitleBack/TitleBack';
import { reqcartdelete, reqcartedit, reqcartlist } from '../../http/api';
import { reducer, initState } from '../Login/user';
import "./Shop.less"
import { List, Switch } from 'antd-mobile';

export default function Shop() {
    // 取出仓库数据
    const [state, dispatch] = useReducer(reducer, initState);

    // 普通商品
    const [cartlist, setcartlist] = useState([]);
    // 万人团
    const [cartgroupen, setcartgroupen] = useState([]);
    // 全选开关状态
    const [allChecked, setallChecked] = useState(false);

    // 首先先定义一个变量isRequest ,默认是true 
    let isRequest = true;

    useEffect(() => {
        // 请求购物车列表
        request();
    }, [])

    // 请求列表封装的函数
    function request() {
        reqcartlist({ uid: state.info.uid }).then(res => {
            if (res.data.code === 200) {
                let arr1 = res.data.list[1].content === null ? [] : res.data.list[1].content;
                let arr2 = res.data.list[0].content === null ? [] : res.data.list[0].content;
                //给每条数据补一个状态;补checked ，代表当前这条数据是否被选中
                arr1.forEach((item) => {
                    let obj1 = cartlist.find(i => i.id === item.id);
                    item.checked = obj1 ? obj1.checked : false;
                })
                arr2.forEach((item) => {
                    let obj2 = cartgroupen.find(i => i.id === item.id);
                    item.checked = obj2 ? obj2.checked : false;
                })
                setcartlist(arr1)
                setcartgroupen(arr2)
                isRequest = true;
            }
        })
    }
    // 删除商品
    function del(id) {
        reqcartdelete({ id }).then(res => {
            if (res.data.code === 200) {
                Toast.info(res.data.msg, 1);
                // 重新请求列表
                request();
            }
        })
    }

    // 商品数量修改
    function edit(type, id, num) {
        if (num <= 1 && type === "1") {
            Toast.info("宝贝不能减少喽", 1)
            return;
        }
        // 节流
        if (isRequest) {
            isRequest = false;
            reqcartedit({ id, type }).then(res => {
                if (res.data.code === 200) {
                    Toast.info(res.data.msg, 1);
                    // 刷新列表
                    request();
                }
            })
        }
    }

    // 修改单个选中状态
    function changeOne(index, type) {
        if (type == 1) {
            cartlist[index].checked = cartlist[index].checked ? false : true;
            setcartlist([...cartlist])
        } else {
            cartgroupen[index].checked = cartgroupen[index].checked ? false : true;
            setcartgroupen([...cartgroupen])
        }
        setallChecked((cartlist.every(item => item.checked)) && (cartgroupen.every(item => item.checked)))
    }

    // 修改全选状态
    function changeAll() {
        // 解决异步问题
        let newAll = !allChecked
        setallChecked(newAll);
        cartlist.forEach(item => {
            item.checked = newAll
        })
        setcartlist([...cartlist])

        cartgroupen.forEach(item => {
            item.checked = newAll
        })
        setcartgroupen([...cartgroupen])
    }

    // 直接计算总价
    let price1 = cartlist.reduce((val, item) => item.checked ? val += item.price * item.num : val, 0);
    // 直接计算总价
    let price2 = cartgroupen.reduce((val, item) => item.checked ? val += item.price * item.num : val, 0);
    let Allprice = price1 + price2;
    return (
        <div className='shop'>
            <TitleBack title={"购物车"}></TitleBack>

            {/* 普通商品 */}
            <ul>
                {
                    cartlist.map((item, index) => {
                        return (
                            <li className="bd-items" key={item.id}>
                                <div className="input">
                                    <List.Item
                                        extra={<Switch color="#ff6040"
                                            checked={item.checked}
                                            onChange={() => changeOne(index, item.type)}
                                        />}
                                    ></List.Item></div>
                                <img src={item.img} alt="" />
                                <h3>{item.goodsname}</h3>
                                <p className="price">&yen; <b>{item.price}</b></p>
                                <span className="span">价格:{(item.checked ? item.price * item.num : 0).toFixed(2)}元</span>
                                <p className="num"><button onClick={() => edit("1", item.id, item.num)}>-</button><span>{item.num}</span><button onClick={() => edit("2", item.id, item.num)}>+</button></p>
                                <button className="del" onClick={() => del(item.id)}>删除</button>
                            </li>
                        )
                    })
                }
            </ul>
            {/* 万人团 */}
            <ul>
                {
                    cartgroupen.map((item, index) => {
                        return (
                            <li className="bd-items" key={item.id}>
                                <div className="input">
                                    <List.Item
                                        extra={<Switch color="#ff6040"
                                            checked={item.checked}
                                            onChange={() => changeOne(index)}
                                        />}
                                    ></List.Item>
                                </div>
                                <img src={item.img} alt="" />
                                <h3>{item.goodsname}</h3>
                                <p className="price">&yen; <b>{item.price}</b></p>
                                <span className="span">价格:{(item.checked ? item.price * item.num : 0).toFixed(2)}元</span>
                                <p className="num"><button onClick={() => edit("1", item.id, item.num)}>-</button><span>{item.num}</span><button onClick={() => edit("2", item.id)}>+</button></p>
                                <button className="del" onClick={() => del(item.id)}>删除</button>
                            </li>
                        )
                    })
                }
            </ul>
            <div className="footer">
                <div className="p"><List.Item
                    extra={<Switch color="#ff6040"
                        checked={allChecked}
                        onChange={() => changeAll()}
                    />}
                ></List.Item>
                </div>
                <span>合计:&yen;{Allprice.toFixed(2)}</span>
            </div>
        </div>
    )
}
